<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>作业 购物车   购书</title>
		<script src="../../vue/vue.js" type="text/javascript" charset="utf-8"></script>
		<style type="text/css">
			#app{
				margin-left: 500px;
			}
		</style>
	</head>
	<body>
		<div id="app">
			<table border="" cellspacing="5" cellpadding="5">
				<tr><!-- 行 -->
					<th>序号</th><!-- 列 -->
					<th>书籍名称</th>
					<th>出版日期</th>
					<th>价格</th>
					<th>购买数量</th>
					<th>操作</th>
				</tr>
				<tbody>
					<tr v-for="(item,index ) in books">
						<td>{{item.id}}</td>
						<td>{{item.name}}</td>
						<td>{{item.date}}</td>
						<!-- <td>{{getFinalPrice(item.price)}}</td> -->
						<td>{{item.price | showPrice}}</td><!-- 调用过滤器 -->
						<td>
							<button type="button" @click="decrement(index)" v-bind:disabled="item.count <= 1">-</button><!-- 当数量小于等于1时候这个按钮不能执行 -->
							{{item.count}}
							<button type="button" @click="increment(index)">+</button>
						</td>
						<td><button type="button" @click="removeBook(index)">移除</button></td>
					</tr>
					
				</tbody>
				
			</table>
			<div v-if="books.length" >
				<h2>总价：{{totalPrice | showPrice}}</h2>
			</div>
			<h2 v-else>购物车为空</h2>
		
		</div>
		<script type="text/javascript">
			var app = new Vue({
				el:'#app',
				data:{
					books:[
						{
							id:1,
							name:'<<算法导论>>',
							date:'2006-9',
							price:85.00,
							count:1
						
						},
						{
							id:2,
							name:'<<Linux>>',
							date:'2007-9',
							price:43.00,
							count:1
						
						},
						{
							id:3,
							name:'<<BC编程思想>>',
							date:'2008-9',
							price:50.00,
							count:1
						
						},
						{
							id:4,
							name:'<<代码大全>>',
							date:'2009-9',
							price:125.00,
							count:1
						
						}
					]
				},
				computed:{//计算属性
					totalPrice(){//计算总价
							let totalPrices = 0 ;
							for(let i = 0 ; i < this.books.length; i++){//这里是通过i索引找到书的值然后在去找价格的值
								totalPrices += this.books[i].price*this.books[i].count;
							}
							return totalPrices;
						}
					},
					totalPric(){//第二种计算总价的方法
						let totalPrices = 0 ;
						for(let ite of this.books){//这里ite拿到的是值
							totalPrices += ite.price*ite.count;
						}
						return totalPrices;
					}
					/* 第三中用高阶函数求总价
						return this.books.reduce(function(preValue,book){
							return preValue +book.price*book.count;
						},0);
					 */
				},
				methods:{
					getFinalPrice(price){//保留两位小数
						return '￥'+price.toFixed(2);
					},
					/* 过滤器 */
					filters:{
						showPrice(price){
							return '￥'+price.toFixed(2);
						}
					},
					increment(index){//增加
						this.books[index].count++;
					},
					decrement(index){//减少
						this.books[index].count--;
					},
					removeBook(index){
						this.books.splice(index,1);//移除
					}
				}
			});
		</script>
	</body>
</html>
